package com.ruoyi.web.controller.youtobemanager;

import com.ruoyi.setlanguages.service.YouTubeManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/youtube/auth")
public class YouTubeAuthController {

    private final YouTubeManager youTubeManager;

    @Autowired
    public YouTubeAuthController(YouTubeManager youTubeManager) {
        this.youTubeManager = youTubeManager;
    }

    /**
     * 清除凭证并重新初始化服务
     */
    @PostMapping("/reinitialize")
    public ResponseEntity<Map<String, Object>> clearAndReinitialize() {
        Map<String, Object> result = new HashMap<>();

        try {
            boolean success = youTubeManager.clearAndReinitializeService();
            result.put("success", success);
            result.put("message", success ? "凭证已清除并重新初始化成功" : "重新初始化失败");
            result.put("authStatus", youTubeManager.getAuthStatus());

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "重新初始化过程中发生错误: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 获取当前认证状态
     */
    @GetMapping("/status")
    public ResponseEntity<Map<String, Object>> getAuthStatus() {
        Map<String, Object> result = new HashMap<>();
        result.put("authStatus", youTubeManager.getAuthStatus());
        result.put("timestamp", System.currentTimeMillis());
        return ResponseEntity.ok(result);
    }

    /**
     * 刷新访问令牌
     */
    @PostMapping("/refresh")
    public ResponseEntity<Map<String, Object>> refreshToken() {
        Map<String, Object> result = new HashMap<>();

        boolean success = youTubeManager.refreshToken();
        result.put("success", success);
        result.put("message", success ? "令牌刷新成功" : "令牌刷新失败");
        result.put("authStatus", youTubeManager.getAuthStatus());

        return ResponseEntity.ok(result);
    }

    /**
     * 仅清除凭证（不重新初始化）
     */
    @PostMapping("/clear")
    public ResponseEntity<Map<String, Object>> clearCredentials() {
        Map<String, Object> result = new HashMap<>();

        boolean success = youTubeManager.clearCredentialsOnly();
        result.put("success", success);
        result.put("message", success ? "凭证已清除" : "清除凭证失败");
        result.put("nextStep", "需要调用重新初始化接口来重新认证");

        return ResponseEntity.ok(result);
    }

    /**
     * 重新初始化服务（在清除凭证后调用）
     */
    @PostMapping("/initialize")
    public ResponseEntity<Map<String, Object>> initializeService() {
        Map<String, Object> result = new HashMap<>();

        boolean success = youTubeManager.forceReinitialize();
        result.put("success", success);
        result.put("message", success ? "服务重新初始化成功" : "重新初始化失败");
        result.put("authStatus", youTubeManager.getAuthStatus());

        return ResponseEntity.ok(result);
    }

    /**
     * 完整的切换账号流程
     */
    @PostMapping("/switch-account")
    public ResponseEntity<Map<String, Object>> switchAccount() {
        Map<String, Object> result = new HashMap<>();

        try {
            // 步骤1: 清除当前凭证
            System.out.println("步骤1: 清除当前凭证...");
            youTubeManager.clearCredentialsOnly();

            // 步骤2: 重新初始化服务（会触发新的OAuth流程）
            System.out.println("步骤2: 重新初始化服务...");
            boolean success = youTubeManager.forceReinitialize();

            result.put("success", success);
            result.put("message", success ?
                    "账号切换成功，请在新的浏览器窗口中完成认证" :
                    "账号切换失败");
            result.put("authStatus", youTubeManager.getAuthStatus());

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "切换账号过程中发生错误: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }
}